const Router = require("@koa/router");
const { examine, users, ObjectId } = require("../models/mongo");
const { sendMail } = require("../node-sendmail");


const router = new Router({
    prefix: "/login",
});

// 自定义中间件
// const { verifyToken } = require("../middleware/verity");

// 获取post的body
const { bodyParser } = require("@koa/bodyparser");
// 加密
const md5 = require("md5");
// token
var jwt = require("jsonwebtoken");

// get读 post增 del删 put改

// 注册逻辑
router.post("/user", bodyParser(), async (ctx) => {
    const { username, password, usertype, eMailcode, eMloginCode } = ctx.request.body;


    if (username && password) {
        const findRes = await users.findOne({ username });
        // console.log("查询结果", findRes);
        if (findRes) {
            //  注册失败
            ctx.body = { error: "注册失败,用户名已存在", Enrollcode: 0 };
        } else if (usertype == 'admin') {
            ctx.body = { error: "违法操作！不能直接注册管理员！！！", Enrollcode: 0 };
        } else {

            // 生成时间戳
            let time = function () {
                const date = new Date(Date.now());
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            }


            // 邮箱格式校验
            function validateEmail(email) {
                const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
                return regex.test(email);
            }

            if (eMailcode) {
                if (validateEmail(eMailcode)) {
                    const OY = await users.findOne({ eMail: eMailcode });
                    if (OY) {
                        let outtime = (Date.now() - OY.eMailtime) > (5 * 60 * 1000)
                        console.log("时间戳", Date.now() - OY.eMailtime, "是否超时", outtime);
                        if (outtime) {

                            ctx.body = { error: "邮箱验证码已超时，请重新获取", Enrollcode: 0 };
                        } else if (OY.eMailcode == eMloginCode) {

                            const resp = await users.findOne({ eMail: eMailcode })

                            if (resp.usertype != 'none') {
                                ctx.body = { error: "该邮箱已被注册！", Enrollcode: 0 };

                            } else {
                                await users.updateOne({ eMail: eMailcode }, { $set: { username, password: md5(password).slice(0, -1), usertype: usertype || "user", time: time(), userstate: 'Active' } })
                                ctx.body = { success: "注册成功,请登录", Enrollcode: 1 };
                            }

                        } else {
                            ctx.body = { error: "邮箱验证码错误！", Enrollcode: 0 };
                        }
                    } else {
                        ctx.body = { error: "请先获取验证码！", Enrollcode: 0 };
                    }

                } else {
                    ctx.body = { error: "邮箱格式错误！", Enrollcode: 0 };
                }
            } else {
                ctx.body = { error: "邮箱不能为空！", Enrollcode: 0 };
            }







            // const insertRes = await users.insertOne({ username, password: md5(password).slice(0, -1), usertype: usertype || "user", time: time(), userstate: 'Active' });

            // //  注册成功
            // ctx.body = { success: "注册成功,请登录", Enrollcode: 1 };
        }
    } else {
        //  注册失败
        ctx.body = { error: "注册失败,用户名或密码不能为空", Enrollcode: 0 };
    }
});
// 登录逻辑
router.post("/login", bodyParser(), async (ctx) => {
    const { username, password } = ctx.request.body;
    if (username && password) {
        const findRes = await users.findOne({ username });
        // console.log("findRes", findRes);

        if (!findRes) {
            ctx.body = { error: "用户名不存在!", logintype: 0 };
        } else {
            const { password: pass, usertype, userstate, ...userRes } = findRes;
            // console.log("zxxsxx", usertype);

            if (pass !== md5(password).slice(0, -1)) {
                // console.log(pass,"密码校验",md5(password).slice(0, -1));

                ctx.body = { error: "密码错误！", logintype: 0 };
            } else if (userstate == 'Locked') {

                ctx.body = { error: "该账户已封禁！", logintype: 0 };
            } else {
                var token = jwt.sign(
                    {
                        exp: Math.floor(Date.now() / 1000) + 60 * 60,
                        user: userRes,
                    },
                    "whale"
                );
                const { password: pass, ...userinfo } = findRes;

                console.log(userinfo);

                ctx.body = { usname: userRes.username, usertype: usertype, success: "登录成功", token, logintype: 2, _id: userRes._id, userstate: userRes.userstate, user: userinfo };
            }
        }
    } else {
        ctx.body = { error: "账号/密码不能为空", logintype: 1 };
    }
});

// token 校验
router.post("/appinit", bodyParser(), async (ctx) => {

    const { token } = ctx.request.body;

    try {
        var decoded = jwt.verify(token, "whale");
        if (decoded) {
            ctx.body = { success: "欢迎回来", initcode: 1, usname: decoded.username };

        }
    } catch (err) {
        // console.log("err登录态", err);
        ctx.body = { error: "登录态已过期，请重新登录", initcode: 0 };
    }



});

// 获取用户列表
router.post("/userlist", bodyParser(), async (ctx) => {

    const { p } = ctx.request.body;
    const count = await users.countDocuments();
    const findRes = await users.find()
        .skip((p - 1) * 10)
        .limit(10)
        .toArray();
    ;
    // console.log("count", Math.ceil(count / 10));
    const findResAll = await users.find()
        .toArray();
    ;
    // console.log("findResAll", findResAll);



    ctx.body = { userlist: findRes, count: Math.ceil(count / 10), userAll: findResAll };


});

// 更新用户信息
router.post("/updateuser", bodyParser(), async (ctx) => {
    const { username, password, usertype, _id, userstate } = ctx.request.body;

    try {

        if (password == "") {

            const OY = await users.findOne({ username });

            if (OY) {
                if (OY._id != _id) {
                    ctx.body = { error: "更新失败，用户名已存在", updatecode: 0 };
                } else {
                    let ssr = await users.updateOne(
                        { _id: new ObjectId(_id) },
                        {
                            $set: { username, usertype, userstate },
                        }
                    );

                    const findRes = await users.findOne({ _id: new ObjectId(_id) });

                    ctx.body = { user: findRes, updatecode: 1 };
                }

            } else {
                let ssr = await users.updateOne(
                    { _id: new ObjectId(_id) },
                    {
                        $set: { username, usertype, userstate },
                    }
                );

                const findRes = await users.findOne({ _id: new ObjectId(_id) });

                ctx.body = { user: findRes, updatecode: 1 };
            }




        } else {
            const OY = await users.findOne({ username });

            if (OY) {
                if (OY._id != _id) {
                    ctx.body = { error: "更新失败，用户名已存在", updatecode: 0 };
                } else {
                    let ssr = await users.updateOne(
                        { _id: new ObjectId(_id) },
                        {
                            $set: { username, password: md5(password).slice(0, -1), usertype, userstate },
                        }
                    );

                    const findRes = await users.findOne({ _id: new ObjectId(_id) });

                    ctx.body = { user: findRes, updatecode: 1 };
                }
            } else {
                let ssr = await users.updateOne(
                    { _id: new ObjectId(_id) },
                    {
                        $set: { username, password: md5(password).slice(0, -1), usertype, userstate },
                    }
                );

                const findRes = await users.findOne({ _id: new ObjectId(_id) });

                ctx.body = { user: findRes, updatecode: 1 };
            }




        }


    } catch {
        ctx.body = { error: "更新失败，出现错误" };

    }

})

// 删除用户
router.post("/deluser", bodyParser(), async (ctx) => {



    const { _id, token } = ctx.request.body;


    try {
        var decoded = jwt.verify(token, "whale");
        if (decoded) {
            try {
                let ssr = await users.deleteOne({ _id: new ObjectId(_id) });
                ctx.body = { msg: "验证完成并删除成功！", delcode: 1 };

            } catch (err) {
                ctx.body = { msg: "删除失败，未找到该用户", delcode: 0 };
            }


        }

    } catch {

        ctx.body = { msg: "验证失败，请重新登录！", delcode: 5 };

    }



})

//查询用户信息
router.post("/selectuser", bodyParser(), async (ctx) => {
    const { SearchCode } = ctx.request.body
    const { p } = ctx.request.body;
    const { msg } = ctx.request.body;

    // console.log(SearchCode, msg);



    switch (SearchCode) {
        case "1":
            try {
                const findRes = await users.find({ _id: new ObjectId(msg) }).skip((p - 1) * 10)
                    .limit(10)
                    .toArray();

                const count = await users.countDocuments({ _id: new ObjectId(msg) });
                // console.log("const", count);

                ctx.body = { userlist: findRes, Seacode: 1, count: Math.ceil(count / 10) };

            } catch {
                ctx.body = { error: "查询失败，未找到该用户", Seacode: 0 };

            }
            break;
        case "2":
            try {
                const findRes = await users.find({ username: { $regex: msg } }).skip((p - 1) * 10)
                    .limit(10)
                    .toArray();

                const count = await users.countDocuments({ username: { $regex: msg } });

                ctx.body = { userlist: findRes, Seacode: 1, count: Math.ceil(count / 10) };

            } catch {
                ctx.body = { error: "查询失败，未找到该用户", Seacode: 0 };

            }
            break;
        case "3":
            try {
                const findRes = await users.find({ usertype: msg }).skip((p - 1) * 10)
                    .limit(10)
                    .toArray();

                const count = await users.countDocuments({ usertype: msg });
                // console.log("const", count);

                ctx.body = { userlist: findRes, Seacode: 1, count: Math.ceil(count / 10) };

            } catch {
                ctx.body = { error: "查询失败，未找到该用户", Seacode: 0 };

            }
            break;
        case "4":
            try {
                const findRes = await users.find({ userstate: msg }).skip((p - 1) * 10)
                    .limit(10)
                    .toArray();

                const count = await users.countDocuments({ userstate: msg });

                ctx.body = { userlist: findRes, Seacode: 1, count: Math.ceil(count / 10) };

            } catch {
                ctx.body = { error: "查询失败，未找到该用户", Seacode: 0 };

            }
            break;
        default:
            ctx.body = { error: "查询失败,请正确输入信息", Seacode: 0 };

            break;
    }

})

// 用户认证
router.post("/Authorization", bodyParser(), async (ctx) => {
    const { _id, Phone, name, IDCard } = ctx.request.body;
    console.log(_id, Phone, name, IDCard);

    let ssr = await users.updateOne(
        { _id: new ObjectId(_id) },
        {
            $set: { usertype: "vip", Phone, name, IDCard },
        }
    );

    const findRes = await users.findOne({ _id: new ObjectId(_id) });

    const { password, Phone: sPhone, IDCard: Id, ...user } = findRes;

    ctx.body = { user: user, updatecode: 1 };


})

// 修改用户信息
router.post("/updateinfo", bodyParser(), async (ctx) => {
    const { _id, username, password, uppassword, setmode } = ctx.request.body;


    const OY = await users.findOne({ username });
    const US = await users.findOne({ _id: new ObjectId(_id) });

    switch (setmode) {
        case "username":
            if (OY) {
                if (OY._id != _id) {
                    ctx.body = { error: "修改失败，用户名已存在", updatecode: 0 };
                } else {
                    let ssr = await users.updateOne(
                        { _id: new ObjectId(_id) },
                        {
                            $set: { username, password: md5(uppassword).slice(0, -1), },
                        }
                    );

                    const findRes = await users.findOne({ _id: new ObjectId(_id) });

                    const { password, Phone: sPhone, IDCard: Id, ...user } = findRes;

                    ctx.body = { user: user, updatecode: 1 };
                }
            } else {

                let ssr = await users.updateOne(
                    { _id: new ObjectId(_id) },
                    {
                        $set: { username, password: md5(uppassword).slice(0, -1), },
                    }
                );

                const findRes = await users.findOne({ _id: new ObjectId(_id) });

                const { password, Phone: sPhone, IDCard: Id, ...user } = findRes;

                ctx.body = { user: user, updatecode: 1 };

            }

            break;
        case "info":
            if (OY) {
                if (US.password != md5(password).slice(0, -1)) {
                    ctx.body = { error: "修改失败，原密码错误", updatecode: 0 };
                } else if (OY._id != _id) {
                    ctx.body = { error: "修改失败，用户名已存在", updatecode: 0 };
                } else {
                    let ssr = await users.updateOne(
                        { _id: new ObjectId(_id) },
                        {
                            $set: { username, password: md5(uppassword).slice(0, -1), },
                        }
                    );

                    const findRes = await users.findOne({ _id: new ObjectId(_id) });

                    const { password, Phone: sPhone, IDCard: Id, ...user } = findRes;

                    ctx.body = { user: user, updatecode: 1 };
                }
            } else {
                if (US.password != md5(password).slice(0, -1)) {
                    ctx.body = { error: "修改失败，原密码错误", updatecode: 0 };
                } else {
                    let ssr = await users.updateOne(
                        { _id: new ObjectId(_id) },
                        {
                            $set: { username, password: md5(uppassword).slice(0, -1), },
                        }
                    );

                    const findRes = await users.findOne({ _id: new ObjectId(_id) });

                    const { password, Phone: sPhone, IDCard: Id, ...user } = findRes;

                    ctx.body = { user: user, updatecode: 1 };
                }
            }
            break;
        default:
            ctx.body = { error: "服务器错误(请求类型错误！)", updatecode: 0 };
            break;
    }







})



// 微信一键登录
const axios = require('axios');
// import axios from 'axios';
router.post("/wxlogin", bodyParser(), async (ctx) => {
    // const { code } = ctx.request.body;
    // ctx.body = { code }

    const { code } = ctx.request.body;
    console.log("code", code);
    // lxz
    // const appId = 'wx3b01d41958167d18';
    // const appSecret = '1d318c8b3ffde83234ee0acfe492e293';

    // ckj
    const appId = 'wxf719cba87dc5d972';
    const appSecret = '93e5767d254743b49fbc0f3f647116c8';

    // zyy
    // const appId = 'wxc3d60596b3313148';
    // const appSecret = '11e670b30770d0391120bfbfa2ab972a';


    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${appSecret}&js_code=${code}&grant_type=authorization_code`;

    console.log("URL:", url);

    try {

        const res = await axios.get(url);

        // ctx.body = { message: "接口测试" }

        const { openid, session_key } = res.data;

        if (openid && session_key) {
            // 生成自定义登录态（例如 token），并返回给前端
            let findres = await users.findOne({ ssid: openid })


            if (findres) {
                // 用户已存在，直接返回登录态
                const { password, Phone: sPhone, IDCard: Id, ssid: ssd, ...user } = findres;
                var token = jwt.sign(
                    {
                        exp: Math.floor(Date.now() / 1000) + 60 * 60,
                        user: user,
                    },
                    "whale"
                );
                ctx.body = { user: user, logincode: 1, token };
                // console.log("ctx", ctx.body);

            } else {
                // 用户不存在，生成新用户记录并返回登录态
                let time = function () {
                    const date = new Date(Date.now());
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const day = String(date.getDate()).padStart(2, '0');
                    const hours = String(date.getHours()).padStart(2, '0');
                    const minutes = String(date.getMinutes()).padStart(2, '0');
                    const seconds = String(date.getSeconds()).padStart(2, '0');
                    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                }

                const use = await users.insertOne({ ssid: openid, username: `微信用户${md5(openid).slice(16, 20)}`, password: md5(openid).slice(0, -1), usertype: "user", time: time(), userstate: 'Active' })



                const findRes = await users.findOne({ _id: new ObjectId(use.insertedId) })
                const { password, Phone: sPhone, IDCard: Id, ssid: ssd, ...user } = findRes;


                var token = jwt.sign(
                    {
                        exp: Math.floor(Date.now() / 1000) + 60 * 60,
                        user: user,
                    },
                    "whale"
                );
                // console.log(token);

                ctx.body = { user: user, logincode: 1, token };
                console.log("ctx", ctx.body);

                console.log("inszhuce", user);





            }

        } else {
            ctx.status = 400;
            ctx.body = { error: '获取 openid 和 session_key 失败' };
        }

        // })

    } catch (error) {
        ctx.status = 500;
        ctx.body = { error: '请求微信接口失败' };
    }
})


// 获取用户领养信息
router.post("/CWLYinfo", bodyParser(), async (ctx) => {
    const { _id } = ctx.request.body;

    const CWLYinfo = await examine.find({ userID: new ObjectId(_id) }).toArray();

    // console.log("领养列表",CWLYinfo);

    ctx.body = { CWLYinfo }


})


// 邮箱验证服务

// 注册发送验证码
router.post("/getmailcode", bodyParser(), async (ctx) => {
    const { eMailcode, username } = ctx.request.body;

    // 生成验证码方法
    function reandomCode(length = 6) {
        const min = Math.pow(10, length - 1); // 最小值（如 100000）
        const max = Math.pow(10, length) - 1; // 最大值（如 999999）
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    // 验证邮箱格式
    function validateEmail(email) {
        const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
        return regex.test(email);
    }
    // console.log("邮箱校验", validateEmail('1803626593@qq.com'));


    let emCode = reandomCode()

    if (validateEmail(eMailcode)) {


        // console.log(ctx.request.body);

        const OY = await users.findOne({ eMail: eMailcode });

        if (OY) {
            let outtime = (Date.now() - OY.eMailtime) > (1 * 60 * 1000)
            console.log("时间戳", Date.now() - OY.eMailtime, "是否超时", outtime);

            if (outtime) {
                // console.log(`${eMailcode}正在重新获取验证码`);

                let eMail = eMailcode
                let msg = `您的验证码是 ${emCode},五分钟内有效。请勿泄露给他人！`
                let title = '小鲸鱼救助中心注册验证'
                sendMail(eMail, title, msg)

                await users.updateOne({ eMail: eMailcode }, { $set: { eMailcode: emCode, eMailtime: Date.now() } })
                ctx.body = { emaillogincode: 1, message: `发送验证码成功！` }
            } else {
                console.log(`${eMailcode}正在重复 获取验证码`);

                ctx.body = { emaillogincode: 0, message: `验证码发送太频繁，请${Math.floor(60 - ((Date.now() - OY.eMailtime) / 1000))}秒后再试!` }
            }
        } else {
            console.log(`${eMailcode}正在注册`);

            let eMail = eMailcode
            let msg = `您的验证码是 ${emCode}`
            let title = '小鲸鱼救助中心注册验证'
            sendMail(eMail, title, msg)
            await users.insertOne({ eMail: eMailcode, eMailcode: emCode, eMailtime: Date.now(), username: '正在注册' + Date.now(), password: '正在注册' + Date.now(), usertype: "none", time: '正在注册' + Date.now(), userstate: 'none' })
            ctx.body = { emaillogincode: 1, message: `发送验证码成功` }

        }


        // ctx.body = { emaillogincode: 1, error: `发送成功!` }

    } else {
        ctx.body = { emaillogincode: 0, message: `邮箱格式不正确!` }

    }


    // ctx.body = { code: 200, mess: `您的验证码是 ${reandomCode()}`, }

})


// 邮箱登录获取验证码
router.post("/getmailloginCode", bodyParser(), async (ctx) => {
    const { eMailcode } = ctx.request.body;

    // 生成验证码方法
    function reandomCode(length = 6) {
        const min = Math.pow(10, length - 1); // 最小值（如 100000）
        const max = Math.pow(10, length) - 1; // 最大值（如 999999）
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    // 验证邮箱格式
    function validateEmail(email) {
        const regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
        return regex.test(email);
    }
    // console.log("邮箱校验", validateEmail('1803626593@qq.com'));


    let emCode = reandomCode()

    if (validateEmail(eMailcode)) {


        // console.log(ctx.request.body);

        const OY = await users.findOne({ eMail: eMailcode });

        if (OY) {
            let outtime = (Date.now() - OY.eMailtime) > (1 * 60 * 1000)
            console.log("时间戳", Date.now() - OY.eMailtime, "是否超时", outtime);

            if (outtime) {
                console.log(`${eMailcode}正在重新获取验证码`);

                let eMail = eMailcode
                let msg = `您的登录验证码是 ${emCode},五分钟内有效。请勿泄露给他人！`
                let title = '小鲸鱼救助中心'
                sendMail(eMail, title, msg)

                await users.updateOne({ eMail: eMailcode }, { $set: { eMailcode: emCode, eMailtime: Date.now() } })
                ctx.body = { emaillogincode: 1, message: `发送验证码成功！` }
            } else {
                console.log(`${eMailcode}正在重复 获取验证码`);

                ctx.body = { emaillogincode: 0, message: `验证码发送太频繁，请${Math.floor(60 - ((Date.now() - OY.eMailtime) / 1000))}秒后再试!` }
            }
        } else {
           
            ctx.body = { emaillogincode: 0, message: `该邮箱尚未注册！` }

        }


        // ctx.body = { emaillogincode: 1, error: `发送成功!` }

    } else {
        ctx.body = { emaillogincode: 0, message: `邮箱格式不正确!` }

    }



})


// 邮箱登录验证
router.post("/mailweblogin", bodyParser(), async (ctx) => {
    const { eMailcode, eMloginCode } = ctx.request.body;

    const OY = await users.findOne({ eMail: eMailcode });
    if (OY) {
        let outtime = (Date.now() - OY.eMailtime) > (5 * 60 * 1000)
        console.log("时间戳", Date.now() - OY.eMailtime, "是否超时", outtime);
        if (outtime) {

            ctx.body = { error: "邮箱验证码已超时，请重新获取", Enrollcode: 0 };
        } else if (OY.eMailcode == eMloginCode) {
            const { password: pass, usertype, userstate, ...userRes } = OY;
            // console.log("zxxsxx", usertype);
            if (userstate == 'Locked') {
                ctx.body = { error: "该账户已封禁！", Enrollcode: 0 };
            } else {
                var token = jwt.sign(
                    {
                        exp: Math.floor(Date.now() / 1000) + 60 * 60,
                        user: userRes,
                    },
                    "whale"
                );
                const { password: pass, ...userinfo } = OY;

                console.log(userinfo);

                ctx.body = { usname: userRes.username, usertype: usertype, success: "登录成功", token, Enrollcode: 1, _id: userRes._id, userstate: userRes.userstate, user: userinfo };
            }

        } else {
            ctx.body = { error: "邮箱验证码错误！", Enrollcode: 0 };
        }
    } else {
        ctx.body = { error: "请先获取验证码！", Enrollcode: 0 };
    }



})




//zgf
//添加用户下的收货地址-zgf
router.post("/address", bodyParser(), async (ctx) => {
    const { _id, address } = ctx.request.body;
    try {
        const result = await users.updateOne(
            { _id: new ObjectId(_id) },
            { $push: { addresses: address } }

        );
        if (result.nModified > 0) {
            ctx.body = {
                code: 200,
                message: "success"
            };
        } else {
            ctx.body = {
                code: 500,
                message: "地址添加失败，可能用户不存在或未修改任何内容"
            };
        }
    } catch (error) {
        console.error('地址添加失败', error);
        ctx.body = {
            code: 500,
            message: "地址添加失败，服务器内部错误"
        };
    }
});
//获取当前用户的收货地址-zgf
router.post("/getaddress", bodyParser(), async (ctx) => {
    const { _id } = ctx.request.body;
    try {
        ctx.body = {
            code: 200,
            addresses: await users.findOne({ _id: new ObjectId(_id) }).then(res => res.addresses),
            index: await users.findOne({ _id: new ObjectId(_id) }).then(res => res.addresses.map((item, index) => index)),
        };
        console.log("address", ctx.body);

    } catch (error) {
        // console.error('获取用户地址失败es4drftgyhujik', error);
        // ctx.status = 500;
        ctx.body = {
            code: 500,
            message: '用户地址列表为空，请添加地址: ' + error.message
        };
    }
});
//删除当前用户的收货地址-zgf
router.post("/deladdress", bodyParser(), async (ctx) => {
    const { _id, arr } = ctx.request.body; // 接收用户 _id 和地址的索引

    console.log(_id, arr);

    let ssr = await users.updateOne(
        { _id: new ObjectId(_id) },
        {
            $set: { addresses: arr },
        }
    );
    const findRes = await users.findOne({ _id: new ObjectId(_id) });
    const { password, Phone: sPhone, IDCard: Id, ...user } = findRes;
    ctx.body = { code: 200, message: '地址删除成功', user: user };
});
//修改当前用户的收货地址-zgf
router.post("/updateaddress", bodyParser(), async (ctx) => {
    console.log('接收到的请求体:egfergeg');
    const { _id, addr } = ctx.request.body;

    console.log(_id, addr);
    // ctx.body = { code: 200, message: '地址修改成功' };


    let ssr = await users.updateOne(
        { _id: new ObjectId(_id) },
        {
            $set: { addresses: addr },
        }
    );
    const findRes = await users.findOne({ _id: new ObjectId(_id) });
    const { password, Phone: sPhone, IDCard: Id, ...user } = findRes;
    ctx.body = { code: 200, message: '地址修改成功', user: user };
})






module.exports = router;
